package com.boarsoft.boar.sys.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.sys.SysPowerBiz;
import com.boarsoft.boar.sys.entity.SysFunc;
import com.boarsoft.boar.sys.entity.SysToken;
import com.boarsoft.boar.sys.entity.SysUser;
import com.boarsoft.common.Util;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("sysPowerBiz")
public class SysPowerBizImpl extends SimpleBizImpl implements SysPowerBiz {
	@Override
	@Transactional(readOnly = true)
	public boolean check(String uid, String func) {
		StringBuilder sb = new StringBuilder();
		sb.append("select count(f.code) from SysUser u join u.roles r join r.funcs f where r.status=");
		sb.append(SysUser.STATUS_INUSE).append(" and u.id='").append(uid);
		sb.append("' and f.code='").append(func).append("' and f.status=").append(SysFunc.STATUS_INUSE);
		Long c = (Long) dao.getValue(sb.toString());
		return c > 0;
	}

	@Override
	@Transactional(readOnly = true)
	public String getUserIdByToken(String token) {
		String hql = String.format("select id from SysUser where token='%s'", token);
		return (String) dao.getValue(hql);
	}

	@Override
	@Transactional(readOnly = true)
	public List<SysFunc> getMyFuncs(String uid, String type) {
		StringBuilder sb = new StringBuilder();
		sb.append("select f from SysUser u join u.roles r join r.funcs f");
		sb.append(" where r.status=").append(SysUser.STATUS_INUSE);
		sb.append(" and u.id='").append(uid).append("' and f.status=");
		sb.append(SysFunc.STATUS_INUSE);
		if (Util.strIsNotEmpty(type)) {
			sb.append(" and f.type='").append(type).append("'");
		}
		sb.append(" order by f.type, f.no");
		return dao.list(sb.toString());
	}

	@Override
	@Transactional(readOnly = true)
	public SysUser getUserByToken(String token) {
		SysUser u = (SysUser) dao.find(SysUser.class, String.format("and token='%s'", token));
		if (u == null) {
			return null;
		}
		SysUser o = new SysUser();
		o.setId(u.getId());
		o.setEmail(u.getEmail());
		o.setPhone(u.getPhone());
		o.setCode(u.getCode());
		o.setName(u.getName());
		o.setDeptId(u.getDeptId());
		o.setCorpId(u.getCorpId());
		o.setType(u.getType());
		return o;
	}

	@Override
	@Transactional(readOnly = true)
	public String checkToken(String token) {
		SysToken o = (SysToken) dao.get(SysToken.class, token);
		return o == null ? null : o.getUserId();
	}
}